/*
 * UserGuard.java
 *
 * Created on July 1, 2007, 4:24 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.auth.service.app;

import java.util.logging.Level;
import org.atomojo.auth.service.db.AuthDB;
import org.atomojo.auth.service.db.Group;
import org.atomojo.auth.service.db.Permission;
import org.atomojo.auth.service.db.User;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.security.ChallengeAuthenticator;
import org.restlet.security.Verifier;

/**
 *
 * @author alex
 */
public class UserGuard extends ChallengeAuthenticator
{

   public final String IDENTITY_ATTR = "org.atomojo.user";
   AuthDB db;
   Permission permission;
   Group group;
   
   /** Creates a new instance of UserGuard */
   public UserGuard(Context context,AuthDB db,ChallengeScheme scheme,String realmName)
   {
      super(context,scheme,realmName);
      this.db = db;
      this.permission = null;
      this.group = null;
      setVerifier(new Verifier() {
         public int verify(Request request, Response response) {
            ChallengeResponse cr = request.getChallengeResponse();
            if (cr==null) {
               return Verifier.RESULT_MISSING;
            }
            try {
               String identifier = cr.getIdentifier();
               char [] secret = cr.getSecret();
               getContext().getLogger().info("Finding user "+identifier);
               User user = AuthResource.findUser(UserGuard.this.db,identifier);
               if (user==null) {
                  getContext().getLogger().info("No such user.");
                  return Verifier.RESULT_INVALID;
               }
               if (secret!=null && user.checkPassword(new String(secret))) {
                  getContext().getLogger().info("Authentication succeeded, checking permissions");
                  if (permission!=null) {
                     if (!user.hasPermission(permission)) {
                        getContext().getLogger().info("User does not have permission "+permission.getName()+","+permission.getUUID());
                        return Verifier.RESULT_INVALID;
                     }
                  }
                  request.getAttributes().put(IDENTITY_ATTR, user);
                  return Verifier.RESULT_VALID;
               } else {
                  getContext().getLogger().info("Password failed: "+(new String(secret)));
               }
            } catch (Exception ex) {
               getContext().getLogger().log(Level.SEVERE,"Cannot process user authentication in guard.",ex);
            }
            return Verifier.RESULT_INVALID;

         }
      });
   }
   
   public void setPermission(Permission permission)
   {
      this.permission = permission;
   }
   
}
